package com.woniuxy.rabbitmq79.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Random;

/**
 * @Author zhangyong
 * @Date 2021/8/11 0011下午 3:20
 */
public class Productor {
    public static void main(String[] args) throws Exception {
        //1.创建连接工厂：创建连接
        ConnectionFactory factory = new ConnectionFactory();

        //2.设置连接参数
        factory.setHost("localhost");   //mq的ip
        factory.setUsername("guest");   //账号
        factory.setPassword("guest");   //密码
        factory.setVirtualHost("/");    //设置虚拟主机 不设置默认/

        //3.创建连接
        Connection connection = factory.newConnection();     //IO异常

        //4.创建通道
        Channel channel = connection.createChannel();

        //获取交换机
        channel.exchangeDeclare("topic_exchange", BuiltinExchangeType.TOPIC);

        //创建路由
        String[] routs = {"sichuan.chengdu.news", "beijing.news"};
        //随机发送
        Random random = new Random();

        //发送消息
        for (int i = 0; i < 10; i++) {
            String message = "big news" + i;
            String route = routs[random.nextInt(2)];
            //
            channel.basicPublish("topic_exchange", route, null, message.getBytes());
        }

        //关闭资源
        channel.close();
        connection.close();
    }
}
